<template>
  <view class="container">
    <!-- 头像 -->
    <view class="avatar-section">
      <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-btn">
        <image class="avatar" :src="form.avatar || defaultAvatar"></image>
      </button>
      <text class="tip">点击修改头像</text>
    </view>

    <!-- 用户名 -->
    <view class="form-item">
      <text class="label">昵称</text>
      <input v-model="form.nickName" placeholder="请输入昵称" class="input"/>
    </view>

    <!-- 手机号 -->
    <view class="form-item">
      <text class="label">手机号</text>
      <input v-model="form.phonenumber" type="number" maxlength="11" placeholder="请输入手机号" class="input"/>
    </view>

    <!-- 保存按钮 -->
    <button class="save-btn" @click="saveProfile">保存</button>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      form: {
        avatar: '',
        nickName: '',
        phonenumber: ''
      },
      defaultAvatar: '/static/icons/dog.png'
    }
  },
  onLoad() {
    const user = uni.getStorageSync('user')
    if (user) {
      this.form = { ...this.form, ...user }
    }
  },
  methods: {
    // 选择头像
    onChooseAvatar(e) {
      this.form.avatar = e.detail.avatarUrl // 临时路径
    },

    // 上传头像到后端
    uploadAvatar(filePath, userId) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `http://192.168.150.215:8080/system/user/avatar`,
          filePath,
          name: 'file',
          header: {
            'Authorization': uni.getStorageSync('token') || ''
          },
          success: (res) => {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              this.form.avatar = data.data // 替换成 OSS 地址
              resolve()
            } else {
              uni.showToast({ title: data.msg || '头像上传失败', icon: 'none' })
              reject(new Error(data.msg))
            }
          },
          fail: (err) => {
            uni.showToast({ title: '头像上传失败', icon: 'none' })
            reject(err)
          }
        })
      })
    },

    // 保存资料
    async saveProfile() {
      if (!this.form.nickName) {
        uni.showToast({ title: '请输入昵称', icon: 'none' })
        return
      }
      const phoneRegex = /^1[3-9]\d{9}$/
      if (this.form.phonenumber && !phoneRegex.test(this.form.phonenumber)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' })
        return
      }

      const user = uni.getStorageSync('user')
      if (!user || !user.userId) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
      }

      try {
        // 判断头像是否是本地临时文件（用户改过头像）
        if (this.form.avatar && this.form.avatar.startsWith('wxfile://')) {
          await this.uploadAvatar(this.form.avatar, user.userId)
        }

        // 调用更新资料接口
        const res = await request({
          url: `/system/user/${user.userId}/profile`,
          method: 'PUT',
          data: this.form
        })

        if (res.code === 200) {
          uni.showToast({ title: '保存成功', icon: 'success' })
          uni.setStorageSync('user', this.form)
          uni.navigateBack()
        }
      } catch (e) {
        console.error('保存资料失败', e)
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40rpx;
  background: #f8f8f8;
  min-height: 100vh;
}
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}
.avatar-btn {
  background: none;
  border: none;
  padding: 0;
}
.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 4rpx solid #eee;
}
.tip {
  font-size: 26rpx;
  color: #888;
  margin-top: 16rpx;
}
.form-item {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
}
.label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
}
.input {
  flex: 1;
  font-size: 30rpx;
  border: none;
  outline: none;
}
.save-btn {
  background: #07c160;
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  margin-top: 40rpx;
}
</style>
